import 'package:english_words/english_words.dart';
import 'package:flutter/material.dart';

/// @date 2020/07/20  18:01
/// @author 程志强
/// @des

class InfiniteListView extends StatefulWidget {
  @override
  _InfiniteListViewState createState() => _InfiniteListViewState();
}

class _InfiniteListViewState extends State<InfiniteListView> {
  static const loadingTag = "loading....";
  List<String> _words = [loadingTag];

  @override
  void initState() {
    super.initState();
    _retriesData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("无限加载列表"),
      ),
      body: ListView.separated(
          itemBuilder: _itemBuilder,
          separatorBuilder: (context, index) => Divider(),
          itemCount: _words.length),
    );
  }

  void _retriesData() {
    Future.delayed(Duration(seconds: 2)).then((value) => {
          setState(() => {
                //重新构建列表
                _words.insertAll(
                    _words.length - 1,
                    // 每次生成20个单词
                    generateWordPairs()
                        .take(20)
                        .map((e) => e.asPascalCase)
                        .toList())
              })
        });
  }

  Widget _itemBuilder(context, index) {
    //如果到了表尾
    if (_words[index] == loadingTag) {
      //不足100条，继续获取数据
      if (_words.length - 1 < 100) {
        //获取数据
        _retriesData();
        // 加载时显示loading
        return Container(
          padding: const EdgeInsets.all(16.0),
          alignment: Alignment.center,
          child: SizedBox(
            width: double.infinity,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                CircularProgressIndicator(
                  strokeWidth: 2.0,
                ),
                SizedBox(width: 20.0,),
                Text(loadingTag)
              ],
            ),
          ),
        );
      } else {
        //已经加载了100条数据，不再获取数据。
        return Container(
          alignment: Alignment.center,
          padding: EdgeInsets.all(16.0),
          child: Text(
            "没有更多数据了...",
            style: TextStyle(color: Colors.grey),
          ),
        );
      }
    }
    return ListTile(
      title: Text(_words[index]),
    );
  }
}
